package thread;

import java.util.Arrays;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 多线程卖票
 * @author ZhouJie
 * @date 2021-10-15 21:49
 */
public class TicketTest {

    public static void main(String[] args) {

        Ticket ticket = new Ticket(50);

        for (String s : Arrays.asList("卖票窗口ONE", "卖票窗口TWO")) {
            new Thread(() -> {
                while (ticket.getNum() > 0){
                    ticket.saleTicket();
                }
            }, s).start();
        }

    }
}

class Ticket{
    /**
     * 票数
     */
    private int num;

    public Ticket(int num){
        this.num = num;
    }

    public int getNum() {
        return num;
    }

    private final Lock lock = new ReentrantLock();

    /**
     * 买票方法
     */
    public  void saleTicket(){
        lock.lock();
        try {
            if (num > 0){
                System.out.println(Thread.currentThread().getName()+"："+num);
                num --;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
